<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <!-- 卡片头部 -->
      <div class="box-card-input">
        <el-input size="small" placeholder="角色名称" v-model="rolerName">
        </el-input>
        <el-select
          v-model="rolerStatus"
          style="margin-right: 10px"
          placeholder="状态"
          clearable
        >
          <!-- <el-option label="全部" value="all"></el-option> -->
          <el-option label="有效" value="1"></el-option>
          <el-option label="无效" value="0"></el-option>
        </el-select>
        <!-- <el-date-picker v-model="startTime" type="date" placeholder="创建时间">
        </el-date-picker> -->

        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>

        <div class="box-card-button">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="queryUserBySearch"
            >搜索</el-button
          >
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="add = true"
            >新增</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="openBatchDel"
            icon="el-icon-delete"
            >批量删除</el-button
          >
        </div>
      </div>

      <!-- 卡片表格区 -->
      <div class="box-card-table">
        <el-table
          :data="tableData"
          @selection-change="tableDataChange"
          ref="multipleTable"
          border
          style="width: 100%"
        >
          <el-table-column width="50" type="selection" align="center">
          </el-table-column>
          <el-table-column prop="id" width="100" label="序号" align="center">
          </el-table-column>
          <el-table-column prop="rolerId" label="角色编码" align="center">
          </el-table-column>
          <el-table-column prop="rolerName" label="角色名称" align="center">
          </el-table-column>
          <el-table-column
            prop="startTime"
            label="生效时间"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="endTime"
            label="失效时间"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="rolerStatus" label="状态" align="center">
            <!-- eslint-disable -->
            <template slot-scope="scope">
              <el-tooltip
                :content="'当前状态: ' + transformStatus(scope.row)"
                placement="top"
              >
                <el-switch
                  v-model="scope.row.rolerStatus"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-value="1"
                  inactive-value="0"
                  @change="statusChange(scope.row)"
                >
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="180"
            class="operation"
          >
            <!-- eslint-disable -->
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                content="修改"
                placement="left-start"
              >
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="openUpdate(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="设置权限"
                placement="left-start"
              >
                <el-button
                  type="success"
                  icon="el-icon-user"
                  @click="getRolesPower(scope.row)"
                  circle
                ></el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="left-start"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="del(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          @current-change="pageChange"
          @prev-click="prev"
          @next-click="next"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 弹出层 -->

    <div class="add">
      <el-dialog title="新增信息" :visible.sync="add" width="40%">
        <div class="add-form">
          <el-form
            ref="addForm"
            :rules="rolerRoles"
            :model="addForm"
            label-width="80px"
          >
            <el-form-item label="角色编码" prop="rolerId">
              <el-input v-model="addForm.rolerId"></el-input>
            </el-form-item>
            <el-form-item label="角色名称" prop="rolerName">
              <el-input v-model="addForm.rolerName"></el-input>
            </el-form-item>
            <el-form-item label="生效时间" prop="startTime">
              <el-date-picker
                v-model="addForm.startTime"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="失效时间" prop="startTime">
              <el-date-picker
                v-model="addForm.endTime"
                type="datetime"
                placeholder="选择日期时间"
                :disabled="addForm.rolerStatus === '1'"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="角色状态" prop="rolerStatus">
              <el-select v-model="addForm.rolerStatus" placeholder="状态">
                <el-option label="有效" value="1"></el-option>
                <el-option label="无效" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="add = false">取 消</el-button>
          <el-button type="primary" @click="addinfo">提 交</el-button>
        </span>
      </el-dialog>
    </div>

    <!-- 修改弹出层 -->
    <div>
      <el-dialog title="修改信息" :visible.sync="update" width="40%">
        <div class="update-form">
          <el-form
            ref="updateForm"
            :rules="rolerRoles"
            :model="updateForm"
            label-width="80px"
          >
            <el-form-item label="角色编码" prop="rolerId">
              <el-input v-model="updateForm.rolerId"></el-input>
            </el-form-item>
            <el-form-item label="角色名称" prop="rolerName">
              <el-input v-model="updateForm.rolerName"></el-input>
            </el-form-item>
            <el-form-item label="角色状态" prop="rolerStatus">
              <el-select v-model="updateForm.rolerStatus" placeholder="状态">
                <el-option label="有效" value="1"></el-option>
                <el-option label="无效" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="生效时间" prop="startTime">
              <el-date-picker
                v-model="updateForm.startTime"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="失效时间" prop="endTime">
              <el-date-picker
                v-model="updateForm.endTime"
                type="datetime"
                placeholder="选择日期时间"
                :disabled="updateForm.rolerStatus === '1'"
              >
              </el-date-picker>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="update = false">取 消</el-button>
          <el-button type="primary" @click="updateinfo">提 交</el-button>
        </span>
      </el-dialog>
    </div>

    <!-- 设置角色权限弹出层 -->
    <div>
      <el-dialog :title="this.getRoleName" :visible.sync="roler" width="40%">
        <span>
          <!-- <h3>角色名称:{{ this.getRoleName }}</h3> -->
          <el-tree
            :data="rolesPower"
            show-checkbox
            node-key="id"
            :default-expanded-keys="[2, 3, 4]"
            :default-checked-keys="checkedKeys"
            :props="defaultProps"
            ref="tree"
            @check-change="handleCheckChange"
          >
          </el-tree>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="roler = false">取 消</el-button>
          <el-button type="primary" @click="upPower">提 交</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// import transListToTreeData from "../utils/treeUtils";
import has from "../../directives/has.js";
export default {
  directives: {
    has,
  },
  inject: ["reload"],
  data() {
    return {
      data: [],
      multipleSelection: [],
      roler: false,
      update: false,
      imports: false,
      add: false,
      date: [],
      value: true,
      checked: true,
      rolerName: "",
      rolerStatus: "",
      currentPage: 1,
      total: 1,
      pageSize: 4,
      pageSizes: [4, 5, 6, 7, 8],
      tableData: [],
      addForm: {
        rolerId: "",
        rolerName: "",
        startTime: Date.now(),
        endTime: "",
        rolerStatus: "1",
      },
      updateForm: {
        rolerId: "",
        rolerName: "",
        rolerStatus: "",
        startTime: "",
        endTime: "",
      },
      rolerRoles: {
        rolerId: [
          { required: true, message: "请输入角色编号", trigger: "blur" },
        ],
        rolerName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        // startTime: [
        //   { required: true, message: "请输入菜单名称", trigger: "blur" },
        // ],
        // rolerStatus: [
        //   { required: true, message: "请输入菜单名称", trigger: "blur" },
        // ],
      },
      idList: [],
      rolesPower: [],
      defaultProps: {
        children: "children",
        label: "menuName",
      },
      expandedKeys: [],
      checkedKeys: [],
      temp: 0,
      getRoleName: "",
    };
  },
  created() {
    this.queryUserBySearch();
  },
  methods: {
    //显示状态值
    transformStatus: function (row) {
      if (row.rolerStatus === "1") {
        return "有效";
      }
      return "无效";
    },
    //提交修改后的权限
    upPower: function () {
      this.$axios
        .post("/api/roler/updateRoles", {
          roles: this.checkedKeys,
          id: this.temp,
        })
        .then((response) => {
          console.log(response);
          if (response.data.code === 200) {
            this.$message({
              type: "success",
              message: "修改成功!",
            });
            this.roler = false;
            this.reload();
          } else {
            this.$message({
              showClose: false,
              type: "warning",
              message: response.data.message,
              duration: 1000,
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    //修改权限
    handleCheckChange() {
      const checkedNodes = this.$refs.tree.getCheckedNodes();
      //  利用这个方法就可以获取到子节点
      // const AllcheckedNodes = [this.$refs.tree.getCheckedNodes(false, true)];
      // 利用这个方法就可以获取到子节点+父节点
      // this.checkedKeys = checkedNodes;
      let arr = [];
      checkedNodes.forEach((item) => {
        if (item.children.length === 0) {
          arr.push(item.id);
        }
      });
      this.checkedKeys = arr;
    },
    //获取角色权限
    getRolesPower: function (row) {
      // this.checkedKeys=[];
      this.temp = row.id;
      this.getRoleName = "设置" + row.rolerName + "权限";
      this.$axios
        .get("/api/roler/queryRoles")
        .then((response) => {
          console.log(response);
          // if (response.data.status === 200) {
          this.rolesPower = response.data.data;
          // }
        })
        .catch((error) => {
          console.log(error);
        });
      this.$axios
        .post("/api/roler/queryRolesById", row.id)
        .then((response) => {
          let arr = response.data.data;
          this.checkedKeys = arr;
          console.log(this.checkedKeys);
        })
        .catch((error) => {
          console.log(error);
        });
      this.roler = true;
    },

    //批量删除对话框
    openBatchDel() {
      this.$confirm("此操作将永久删除信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .post("/api/roler/rolesBatchDelete", this.idList)
            .then((response) => {
              console.log(response);
              if (response.data.code === 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.reload();
              } else {
                this.$message({
                  showClose: false,
                  type: "warning",
                  message: response.data.message,
                  duration: 1000,
                });
              }
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //批量删除
    tableDataChange(val) {
      let temp = val;
      console.log(val);
      temp.forEach((element) => {
        this.idList.push(element.id);
      });
      console.log(this.idList);
    },
    //表格多选相关函数
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //搜索相关函数
    queryUserBySearch: function () {
      console.log(this.date);
      let startTime = this.date[0];
      let endTime = this.date[1];
      let query = {
        rolerName: this.rolerName,
        rolerStatus: this.rolerStatus,
        startTime: startTime,
        endTime: endTime,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
      };
      this.$axios
        .post("api/roler/queryRolerBySearch", query)
        .then((response) => {
          console.log(response);
          this.tableData = response.data.data;
          this.total = response.data.total;
        })
        .catch((error) => {
          console.log(error);
        });
    },

    //每页数据展示条数改变函数
    handleSizeChange: function (val) {
      this.queryUserBySearch();
    },
    //当前页改变函数

    pageChange(currentPage) {
      this.currentPage = currentPage;
      this.queryUserBySearch();
    },
    prev() {
      this.currentPage--;
      this.queryUserBySearch();
    },
    next() {
      this.currentPage++;
      this.queryUserBySearch();
    },

    //获取数据函数
    getData: function () {
      this.$axios
        .get("/api/roler/queryRoler", {
          params: {
            count: this.pageSize,
            currentPage: this.currentPage,
          },
        })
        .then((response) => {
          console.log(response);
          // if (response.data.status == "200") {
          this.tableData = response.data.data;
          this.total = response.data.total;
          console.log(this.total);
          // }
        })
        .catch((error) => {
          console.log(error);
        });
    },

    //增加数据函数
    addinfo: function () {
      this.$axios
        .post("/api/roler/insertRoler", this.addForm)
        .then((response) => {
          console.log(response);
          if (response.data.code === 200) {
            this.$message({
              showClose: false,
              type: "success",
              message: "添加信息成功!",
              duration: 1000,
            });
            this.add = false;
            this.reload();
          } else {
            this.$message({
              showClose: false,
              type: "warning",
              message: response.data.message,
              duration: 1000,
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },

    //更新数据函数
    openUpdate: function (row) {
      this.update = true;
      this.updateForm = {
        id: row.id,
        rolerId: row.rolerId,
        rolerName: row.rolerName,
        startTime: row.startTime,
        endTime: row.endTime,
        rolerStatus: row.rolerStatus,
      };
    },
    updateinfo: function () {
      this.$axios
        .post("/api/roler/updateRoler", this.updateForm)
        .then((response) => {
          // console.log(response);
          if (response.data.code === 200) {
            this.$message({
              showClose: false,
              type: "success",
              message: "修改信息成功!",
              duration: 1000,
            });
            this.update = false;
            this.reload();
          } else {
            this.$message({
              showClose: false,
              type: "warning",
              message: response.data.message,
              duration: 1000,
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },

    //删除数据函数
    del: function (row) {
      this.$confirm("此操作将永久删除信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .post("/api/roler/deleteRoler", row.id)
            .then((response) => {
              console.log(response);
              if (response.data.code === 200) {
                this.$message({
                  showClose: false,
                  type: "success",
                  message: "删除信息成功!",
                  duration: 1000,
                });
                this.reload();
              } else {
                this.$message({
                  showClose: false,
                  type: "warning",
                  message: response.data.message,
                  duration: 1000,
                });
              }
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //修改状态
    statusChange: function (row) {
      (this.updateForm = {
        id: row.id,
        rolerId: row.rolerId,
        rolerName: row.rolerName,
        rolerStatus: row.rolerStatus,
        startTime: row.startTime,
        endTime: row.rolerStatus==='0'?new Date():null
      }),
      console.log(this.updateForm);
        this.$axios
          .post("/api/roler/updateStatus", this.updateForm)
          .then((response) => {
            if (response.data.code === 200) {
              this.$message({
                type: "success",
                message: "修改成功",
              });
              this.reload();
            } else {
              this.$message({
                showClose: false,
                type: "warning",
                message: response.data.message,
                duration: 2000,
              });
            }
          })
          .catch((error) => {
            console.log(error);
          });
    },
  },
};
</script>

<style scoped>
.box-card .box-card-input {
  margin-bottom: 15px;
}
.box-card .box-card-input .el-input {
  display: inline-block;
  width: 200px;
  margin-right: 15px;
  margin-bottom: 10px;
}
.el-dialog__body {
  padding-top: 0;
}
.el-form .el-input {
  width: 250px;
}

.el-form .el-select {
  width: 250px;
}
</style>